package com.example.fabric.ctrl;

import com.example.fabric.FabricDemo;
import com.example.fabric.InitFabricClient;
import com.example.fabric.config.FabricConfig;
import com.example.fabric.dto.EvidenceDto;
import com.example.fabric.utils.GsonUtil;
import com.example.fabric.utils.R;
import com.google.gson.Gson;
import io.swagger.annotations.ApiOperation;
import org.hyperledger.fabric.sdk.ChaincodeID;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 86182
 * \* Date: 2020/4/12
 * \* Time: 19:40
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
@RestController
public class EvdController {

    @Autowired
    private InitFabricClient client;

    @Autowired
    private FabricConfig fabricConfig;

    private final static ChaincodeID ccId = ChaincodeID.newBuilder().setName("evid").build();

    @ApiOperation("创建存证")
    @RequestMapping(value="/storage", method = RequestMethod.POST)
    public void storage(@RequestBody EvidenceDto dto) {
        String funcName = "storage";
        String content = GsonUtil.toJson(dto);
        FabricDemo.sendTranstion(client.getHfclient(), client.getChannel(), ccId, client.getUser(), fabricConfig.getTxTimeout(), funcName, content);
    }

    @ApiOperation("更新存证")
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public void update(@RequestBody EvidenceDto dto) {
        String funcName = "update";
        String content = GsonUtil.toJson(dto);
        FabricDemo.sendTranstion(client.getHfclient(), client.getChannel(), ccId, client.getUser(), fabricConfig.getTxTimeout(), funcName, content);
    }

    @ApiOperation("查询存证")
    @RequestMapping(value="/load", method = RequestMethod.GET)
    public R load(@RequestParam(name = "evdID") String evdID) {
        String funcName = "load";
        try {
            String ret = FabricDemo.QueryChaincode(client.getHfclient(), client.getChannel(), ccId, funcName, evdID);
            if (ret.equals("")) {
                return R.error(-1, "peer query not diff");
            }
            return R.ok(ret);
        } catch (ProposalException | InvalidArgumentException e) {
            e.printStackTrace();
        }

        return R.error(-1, "peer query exception");
    }
}
